<?php
namespace frontend\controllers;

use backend\models\NewsNom;
use backend\models\NewsTag;
use Yii;
use yii\base\InvalidParamException;
use yii\db\Query;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

use common\models\User;
use backend\models\NewsFlash;
use backend\models\NewsTagRela;
use backend\models\NewsBanner;
use backend\models\Contact;
use yii\data\Pagination;
use yii\web\Response;
use yii\web\NotFoundHttpException;
/**
 * Site controller
 */
class SiteController extends Controller
{
    public $layout = "main-single";
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *首页
     * @return mixed
     */
    public function actionIndex()
    {
        $banners = $this->getBanners();
        $news = $this->getAllNews();
        $newsupdate = $this->getNewsUpdate();
        $last = end($news);

        return $this->render('index',['banners' => $banners, 'news' => $news,'newsupdate' => $newsupdate,'lasttime' => $last['ptime'], 'isfirst' => true]);
    }

    /**
     * 获取banner图片信息
     */
    private function getBanners(){
        return NewsBanner::find()->where(['status' => NewsNom::NEWS_STATUS_NOM])->orderBy("ptime desc")->limit(5)->asArray()->all();
    }

    /**
     * 获取所有新闻信息
     */
    private function getAllNews(){
        $news = NewsNom::find()->where(['status' => [NewsNom::NEWS_STATUS_NOM,NewsNom::NEWS_STATUS_WAT]])
                ->andWhere(['<=','ptime',date("Y-m-d H:i:s",time())])
            ->with("userInfo")
            ->orderBy("ptime desc")->limit(10)->asArray()->all();

        return $news;
    }

    /**
     * 获取所有新闻信息
     */
    private function getNewsUpdate(){
        $news = NewsFlash::find()->where(['status' => [NewsNom::NEWS_STATUS_NOM,NewsNom::NEWS_STATUS_WAT]])
            ->andWhere(['<=','ptime',date("Y-m-d H:i:s",time())])
            ->orderBy("ptime desc")->limit(10)->asArray()->all();

        return $news;
    }

    public function actionIndexmore()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $lasttime = Yii::$app->request->get('lasttime','');

        $news = NewsNom::find()->where(['status' => [NewsNom::NEWS_STATUS_NOM,NewsNom::NEWS_STATUS_WAT]])
            ->andWhere(['<','ptime',$lasttime])
            ->orderBy('ptime desc')->limit(10)->asArray()->all();

        if( !$news ) return ['ret' => false];
        $last = end($news);

        return [
            'ret' => true,
            'data' => $this->renderAjax('indexitem', ['news' => $news, 'banners' => array(),'lasttime' => $last['ptime'],'isfirst' => false]),
            'lasttime' => $last['ptime']
        ];
    }

    /**
     * 快
    */
    public function actionNews(){
        $news = $this->getAllNews();
        $last = end($news);

        return $this->render('news',['news' => $news,'lastid' => $last['id']]);
    }

    /**
     * 快
    */
    public function actionBid(){
        $models = NewsFlash::find()->where(['status' => [NewsNom::NEWS_STATUS_NOM,NewsNom::NEWS_STATUS_WAT]])
            ->andWhere(['<=','ptime',date("Y-m-d H:i:s",time())])
            ->orderBy("ptime desc")->limit(15)->asArray()->all();


        return $this->render('bid',['news' => $models]);
    }

    /**
     * 加载更多
     * @return array
     */
    public function actionGetmore(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $time = Yii::$app->request->get('id',1);

        $count = NewsFlash::find()->where(['status' => 0])->andWhere(['>','ctime',$time])->count();
        return [
            'ret' => true,
            'count' => $count,
        ];
    }

    /**
     * 点赞
     * @return array
     */
    public function actionUp(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $id = Yii::$app->request->get('id',0);

        $ret = NewsFlash::updateAllCounters(['up' => 1],['id' => $id]);
        if( $ret ){
            $return = true;
        }else{
            $return = false;
        }
        return [
            'ret' => $return
        ];
    }

    /**
     * 普通点赞
     * @return array
     */
    public function actionNomup(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $id = Yii::$app->request->get('id',0);

        $ret = NewsNom::updateAllCounters(['up' => 1],['id' => $id]);
        if( $ret ){
            $return = true;
        }else{
            $return = false;
        }
        return [
            'ret' => $return
        ];
    }

    /**
     * 下拉加载旧新闻
     * @return array|bool
     */
    public function actionGetnews(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $lasttime = Yii::$app->request->get("lasttime");

        $models = NewsFlash::find()->where(['status' => [NewsNom::NEWS_STATUS_NOM,NewsNom::NEWS_STATUS_WAT]])
            ->andWhere(['<','ptime',$lasttime])
            ->orderBy("ptime desc")->limit(15)->asArray()->all();

        if( !$models ) return false;

        $last = end($models);

        $news = array();
        $now = time();
        $weekend = array('星期天','星期一','星期二','星期三','星期四','星期五','星期六',);
        foreach ( $models as $item ){
            $publish = $item['ptime'];
            $wek = $weekend[date("w", strtotime($item['ptime']))];
            $days = round(($now - strtotime($item['ptime']))/3600/24);
            if( $days == 0 )
                $days = '今天';
            elseif( $days == 1 )
                $days = '昨天';
            elseif( $days == 2 )
                $days = '前天';
            else
                $days = $days.' 天前';

            $daystr = "{$publish} · {$wek} · {$days}";
            $news[$publish]['datestr'] = $daystr;
            $news[$publish]['list'][] = $item;
        }
        return [
            'ret' => true,
            'data' => $this->renderAjax('items', ['news' => $news]),
            'lasttime' => $last['ptime']
        ];
    }

    /**
     * 快 详情页
     * @return string
     */
    public function actionDetail(){
        $id = Yii::$app->request->get('id',0);

        if (($model = NewsFlash::findOne($id)) == null) {
            throw new NotFoundHttpException('您请求的页面不存在');
        }

        return $this->render('detail',['model' => $model]);
    }


    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }


    /**
     * tag页面
     * @return string
     */
    public function actionTag(){
        $id = (int) Yii::$app->request->get('id',0);

        $tag = NewsTag::findOne($id);

        $rows = NewsTagRela::find()->where(['tagid' => $id])->asArray()->all();
        $newsids = array();
        foreach ( $rows as $value ){
            $newsids[] = $value['newsid'];
        }

        $news = NewsNom::find()->where(['id' => $newsids,'status' => NewsNom::NEWS_STATUS_NOM])
            ->orderBy("id desc")
            ->limit(10)->asArray()->all();

        $last = end($news);
        return $this->render('tag',['news' => $news,'tag' => $tag,'tagid' => $id,'lastid' => $last['id']]);
    }

    /**
     * tag页面下拉加载
     */
    public function actionTagmore(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $tagid = (int) Yii::$app->request->get('tagid',0);
        $lastid = (int) Yii::$app->request->get('lastid',0);

        $rows = NewsTagRela::find()->where(['tagid' => $tagid])->asArray()->all();
        $newsids = array();
        foreach ( $rows as $value ){
            $newsids[] = $value['newsid'];
        }

        $news = NewsNom::find()->where(['id' => $newsids,'status' => NewsNom::NEWS_STATUS_NOM])
            ->andWhere(['<','id',$lastid])
            ->orderBy("id desc")
            ->limit(10)->asArray()->all();

        if( !$news ) return ['ret' => false];
        $last = end($news);

        return [
            'ret' => true,
            'data' => $this->renderAjax('tagitem', ['news' => $news]),
            'lastid' => $last['id']
        ];
    }

    public function actionHome(){
        $id = (int) Yii::$app->request->get('id',0);
        $userinfo = $this->getUserInfo($id);
        $news = NewsNom::find()->where(['authorid' => $id,'status' => NewsNom::NEWS_STATUS_NOM])
            ->orderBy('id desc')->limit(10)->asArray()->all();

        $last = end($news);
        return $this->render('home',['news' => $news,'userinfo' => $userinfo,'authorid' => $id,'lastid' => $last['id']]);
    }

    /**
     * 用户主页下拉加载
     */
    public function actionHomemore(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $authorid = (int) Yii::$app->request->get('authorid',0);
        $lastid = (int) Yii::$app->request->get('lastid',0);

        $news = NewsNom::find()->where(['authorid' => $authorid,'status' => NewsNom::NEWS_STATUS_NOM])->andWhere(['<','id',$lastid])
            ->orderBy('id desc')->limit(10)->asArray()->all();

        if( !$news ) return ['ret' => false];
        $last = end($news);

        return [
            'ret' => true,
            'data' => $this->renderAjax('homeitem', ['news' => $news]),
            'lastid' => $last['id']
        ];
    }

    public function actionArticle(){
        $id = (int) Yii::$app->request->get('id',0);

        $news = NewsNom::find()->where(['id' => $id,'status' => NewsNom::NEWS_STATUS_NOM])->asArray()->one();
        if( !$news ){
            throw new NotFoundHttpException('您请求的页面不存在');
        }

        $userinfo = $this->getUserInfo($news['authorid']);
        $relatnews = $this->articlerelat( $id );//相关文章

        return $this->render('article',['news' => $news,'relatnews' => $relatnews,'userinfo' => $userinfo]);
    }

    public function actionBidinfo(){
        $id = (int) Yii::$app->request->get('id',0);

        $news = NewsFlash::find()->where(['id' => $id,'status' => NewsNom::NEWS_STATUS_NOM])->asArray()->one();

        if( !$news ){
            throw new NotFoundHttpException('您请求的页面不存在');
        }

        $userinfo = $this->getUserInfo($news['authorid']);
        $relatnews = $this->articlerelat( $id );//相关文章

        return $this->render('article',['news' => $news,'relatnews' => $relatnews,'userinfo' => $userinfo]);
    }

    /**
     * 相关文章id
     */
    private function articlerelat( $newsid ){
        //select newsid,count(*) from news_tag_rela where tagid in (11,12,13,14) group by newsid order by newsid desc;
        $newstags = NewsTagRela::getTagidByNewsid($newsid);
        $tags = array();
        foreach ( $newstags as $item ){
            $tags[] = $item;
        }

        $query = new Query();
        $rows = $query->select('newsid,count(*) as times')->where(['tagid' => $tags])->andWhere(['<>','newsid',$newsid])
                    ->from('news_tag_rela')->groupBy('newsid')->orderBy('times desc')->all();

        $newsids = array();
        if( $rows ){
            $tow = array_slice($rows,0,2);
            foreach ( $tow as $value ){
                $newsids[] = $value['newsid'];
            }
        }else{
            //取两个幻灯片文章
            $newsids = NewsBanner::find()->select('newsid')->orderBy('ctime desc')->limit(2)->asArray()->all();
            foreach ( $newsids as $value ){
                $newsids[] = $value['newsid'];
            }
        }

        $relatenews =  NewsNom::find()->where(['id' => $newsids,'status' => NewsNom::NEWS_STATUS_NOM])->asArray()->all();
        return $relatenews;
    }

    public function actionAjaxSaveContact(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $contact = Yii::$app->request->post();
        $contact['Contact']['ctime'] = date("Y-m-d H:i:s",time());

        $model = new Contact();
        if( $model->load($contact) && $model->validate($contact) ){
            if( $model->save() ){
                return ['ret' => true];
            }
        }

        return ['ret' => false,'error' => $model->errors];
    }


    private function getUserInfo($id){
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            return false;
        }
    }
}
